Skip to content

在 linux 服务器上安装 redis 源码包(源码包)

安装流程

shell
# 安装 GCC 编译器
yum -y install gcc

# 创建 redis 家目录
cd /usr/local && mkdir redis && cd redis

# 下载 redis 安装包(wget 下载的文件在当前目录下)
wget http://download.redis.io/releases/redis-7.2.2.tar.gz

# 解压
tar -xvf redis-7.2.2.tar.gz

# 编译
cd /usr/local/redis/redis-7.2.2 && make && make install

修改 redis 配置文件

为了方便管理,我们通常会将 Redis 的配置文件和数据目录放到标准位置。

shell
# 创建配置文件目录
sudo mkdir -p /etc/redis 

# 创建数据存储目录
sudo mkdir -p /var/lib/redis

# 创建日志目录
sudo mkdir -p /var/log/redis

# 将源码中的 redis.conf 复制到配置目录(路径请按你的解压目录调整)
sudo cp /usr/local/redis/redis-7.2.2/redis.conf /etc/redis/

# 编辑 redis 配置文件
sudo vim /etc/redis/redis.conf

redis.conf 中建议核对:

conf
daemonize yes
pidfile /var/run/redis/redis-server.pid
logfile /var/log/redis/redis-server.log
dir /var/lib/redis
requirepass your_strong_password_here

使用 systemd 托管时,更推荐 daemonize nosupervised systemd,由 systemd 管理前台进程;上面为传统后台写法,按团队规范二选一。

创建 Systemd 服务文件

shell
# 创建 redis 用户和组
sudo adduser --system --group --no-create-home redis
sudo chown -R redis:redis /var/lib/redis /var/log/redis /var/run/redis

# 创建&编辑配置 Systemd 服务文件
sudo vi /etc/systemd/system/redis.service

# 添加如下内容
[Unit]
Description=Redis In-Memory Data Store
After=network.target

[Service]
User=redis
Group=redis
WorkingDirectory=/var/lib/redis
ExecStart=/usr/local/bin/redis-server /etc/redis/redis.conf
ExecStop=/usr/local/bin/redis-cli shutdown
Restart=always
PIDFile=/var/run/redis/redis-server.pid

[Install]
WantedBy=multi-user.target

redis 常用命令

  1. 服务命令
shell
systemctl daemon-reload # 重新加载 systemd 配置
systemctl start redis    # 启动服务
systemctl reload redis   # 重新加载redis.conf配置文件
systemctl restart redis  # 重启服务
systemctl stop redis     # 停止服务

systemctl enable redis     # 开机自启
systemctl disable redis    # 开机不自启
systemctl list-unit-files | grep redis   # 检查redis是否已经安装了开机自动启动

systemctl status redis   # 查看redis状态

ps -ef | grep redis          # 查看进程redis进程
kill -9 pid                  # 杀掉 redis 进程
netstat -antlp | grep redis  # 查看redis服务端口

yum remove redis             # yum 卸载redis软件包
  1. redis 终端命令
shell
set key value
get key
keys *
del key

配置防火墙

你的服务器启用了防火墙(如 firewalld),并且需要从外部访问 Redis,你需要开放 Redis 的端口(默认为 6379)。

shell
sudo firewall-cmd --zone=public --add-port=6379/tcp --permanent
sudo firewall-cmd --reload